package edu.uoc.tdp.client.estudiants;

import edu.uoc.tdp.beans.conexio.Estudiant;
import edu.uoc.tdp.beans.estudiants.Inscripcio;
import edu.uoc.tdp.beans.proves.Prova;
import edu.uoc.tdp.common.EOlympicsException;
import edu.uoc.tdp.common.RemotEstudiantsInterface;
import edu.uoc.tdp.common.TDSLanguageUtils;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;

/**
 * Pantalla que mostra el detall de la prova/ronda seleccionada a la pantalla PantallaConsultaProves
 * @author Jordi
 */
public class PantallaDetall extends javax.swing.JFrame {

    private RemotEstudiantsInterface remot;
    private Prova prova;
    private Estudiant estudiant;
    private String tipusronda;
    private int nombreinscrits;
    
    
    /**
     * Constructor amb dos paràmetres   
     * @param pEsrudiant           Identificador de l'estudiant actual
     * @param pRemot               Remot que ens permet connectar amb el servidor
     */
    public PantallaDetall(Prova pProva,Estudiant pEstudiant,RemotEstudiantsInterface pRemot) {
        remot = pRemot;  
        prova = pProva;
        estudiant = pEstudiant;
        nombreinscrits = 0;
        
        initComponents();
        carregainicial(prova);
        
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {            
            public void windowClosing(java.awt.event.WindowEvent evt) {
                tancarFinestra(evt);
            }
        });
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "INFORMACIO DE LA PROVA", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14), java.awt.Color.blue)); // NOI18N

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel3.setText("Ronda:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel2.setText("Preguntes:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel4.setText("Inscripcio:");

        jLabel5.setText("jLabel5");

        jLabel6.setText("jLabel6");

        jLabel7.setText("jLabel7");

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel8.setText("Places:");

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel9.setText("Classificació:");

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel10.setText("Realització:");

        jLabel11.setText("jLabel11");

        jLabel12.setText("jLabel12");

        jLabel13.setText("jLabel13");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4))
                .addGap(126, 126, 126)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(jLabel6)
                    .addComponent(jLabel5))
                .addGap(177, 177, 177)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(jLabel9)
                    .addComponent(jLabel10))
                .addGap(137, 137, 137)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel13)
                    .addComponent(jLabel11)
                    .addComponent(jLabel12))
                .addContainerGap(210, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel8)
                    .addComponent(jLabel11)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel9)
                    .addComponent(jLabel12)
                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel10)
                    .addComponent(jLabel13)
                    .addComponent(jLabel7))
                .addContainerGap(11, Short.MAX_VALUE))
        );

        jLabel14.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel14.setForeground(new java.awt.Color(0, 0, 255));
        jLabel14.setText("LLISTAT DE PARTICIPANTS");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setEnabled(false);
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("ALTA");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("BAIXA");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Tornar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel14)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 895, Short.MAX_VALUE))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3)
                        .addGap(35, 35, 35))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addComponent(jLabel14)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
     /**
     * Obre la pantalla de validació de la inscricpió si l'estudiant no s'ha inscrit previament
     * @param evt               disparador
     */
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            if(remot.ComprovaInscripcio(prova.getIdProva(), estudiant.getIdIntern())){
                JOptionPane.showMessageDialog 
                (null, TDSLanguageUtils.getMessage("estudiants.pantalla.detall.alerta.inscr.miss"), 
                 TDSLanguageUtils.getMessage("estudiants.pantalla.detall.alerta.inscr.title"),
                 JOptionPane.WARNING_MESSAGE);
            } else if(nombreinscrits >= prova.getNombrePlaces()){
                JOptionPane.showMessageDialog 
                (null, TDSLanguageUtils.getMessage("estudiants.pantalla.detall.alerta.places.miss"),
                 TDSLanguageUtils.getMessage("estudiants.pantalla.detall.alerta.places.title"),
                 JOptionPane.WARNING_MESSAGE);
              } else {
                new PantallaValidacio(prova,estudiant,remot).setVisible(true); ;
                this.dispose();
                }
        } catch (RemoteException ex) {
            JOptionPane.showMessageDialog 
             (null,TDSLanguageUtils.getMessage("estudiants.common.error.conexio.miss"),
              TDSLanguageUtils.getMessage("estudiants.common.error.literalerror"), JOptionPane.ERROR_MESSAGE);
        } catch (EOlympicsException ex) {
            JOptionPane.showMessageDialog 
             (null, ex.getMessage(), TDSLanguageUtils.getMessage("estudiants.common.error.literalerror"), JOptionPane.ERROR_MESSAGE);
        }
            
}//GEN-LAST:event_jButton1ActionPerformed

     /**
     * Dona de baixa l'estudiant d'una prova si abans hi estava inscrit
     * @param evt               disparador
     */
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {
            if(!remot.ComprovaInscripcio(prova.getIdProva(), estudiant.getIdIntern())){
                JOptionPane.showMessageDialog 
                (null, TDSLanguageUtils.getMessage("estudiants.pantalla.detall.alerta.baixa.miss"),
                 TDSLanguageUtils.getMessage("estudiants.pantalla.detall.alerta.baixa.title"),
                 JOptionPane.WARNING_MESSAGE);
            } else {
                int n = JOptionPane.showConfirmDialog(
                null,
                TDSLanguageUtils.getMessage("estudiants.pantalla.detall.pregunta.baixa.miss") + prova.getDescripcio() + "?",
                TDSLanguageUtils.getMessage("estudiants.pantalla.detall.pregunta.baixa.title"),
                JOptionPane.YES_NO_OPTION); 
                    
                if (n == 0){
                    boolean Esborrat = remot.Esborrar(prova.getIdProva(), estudiant.getIdIntern());
                    if (Esborrat){
                    JOptionPane.showMessageDialog 
                    (null, TDSLanguageUtils.getMessage("estudiants.pantalla.detall.confirma.baixa.miss"),
                     TDSLanguageUtils.getMessage("estudiants.pantalla.detall.confirma.baixa.title"), JOptionPane.INFORMATION_MESSAGE);
                    }
                    
                    this.dispose();
                }
            }
           
        } catch (RemoteException ex) {
            JOptionPane.showMessageDialog 
             (null,TDSLanguageUtils.getMessage("estudiants.common.error.conexio.miss"),
              TDSLanguageUtils.getMessage("estudiants.common.error.literalerror"), JOptionPane.ERROR_MESSAGE);
        } catch (EOlympicsException ex) {
            JOptionPane.showMessageDialog 
             (null, ex.getMessage(), TDSLanguageUtils.getMessage("estudiants.common.error.literalerror"), JOptionPane.ERROR_MESSAGE);
        }
}//GEN-LAST:event_jButton2ActionPerformed

     /**
     * Tanca la finestra
     * @param evt               disparador
     */
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
            tancarFinestraboto(evt);
}//GEN-LAST:event_jButton3ActionPerformed
     /**
     * Tancament de la finestra des de d'un windowevent
     * @param evt               disparador
     */
    private void tancarFinestra(java.awt.event.WindowEvent evt) {
        dispose();
        System.exit(0);
    }
     /**
     * Tancament de la finestra des des del boto tancar
     * @param evt               disparador
     */   
    private void tancarFinestraboto (java.awt.event.ActionEvent evt) {
        dispose();
    }
 
       /**
     * Fa la primera carrega de la pantalla. Posant el valor a els elements de texte i fent la carrega
     * dels estudiants inscrits en la prova.
     * @param evt               disparador
     */
    private void carregainicial(Prova prova){
        
        TDSLanguageUtils.setDefaultLanguage("edu/uoc/tdp/i18n/messages");
        this.setTitle(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.nom"));
        
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder
           (null, TDSLanguageUtils.getMessage("estudiants.pantalla.detall.panel.title") 
            + prova.getDescripcio(), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
            javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14), java.awt.Color.blue));

        jLabel3.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.panel.field1"));
        jLabel2.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.panel.field2"));
        jLabel4.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.panel.field3"));
        jLabel8.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.panel.field4"));
        jLabel9.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.panel.field5"));
        jLabel10.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.panel.field6"));
        jLabel14.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.table.title"));
        jButton1.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.Button.alta"));
        jButton2.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.Button.baixa"));
        jButton3.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.Button.tornar"));        

        try{
            tipusronda = tipusderonda(prova);
            
            if(tipusronda.equals("F")){
                jLabel5.setText(TDSLanguageUtils.getMessage("estudiants.common.final"));
                jLabel6.setText(prova.getRondaFinal().getNombrePreguntes().toString());
                jLabel7.setText(prova.getDataIniInscripcio().toString() + " a " + prova.getDataFiInscripcio().toString());
            } else {
                    jLabel5.setText(TDSLanguageUtils.getMessage("estudiants.common.eliminatoria"));
                    jLabel6.setText(prova.getRondaEliminatoria().getNombrePreguntes().toString());
                    jLabel7.setText(prova.getDataIniInscripcio().toString() + " a " + prova.getDataFiInscripcio().toString());                    
              }

            jLabel11.setText(prova.getNombrePlaces().toString());
            
            if(tipusronda.equals("E")){
                jLabel12.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.first10"));
            } else jLabel12.setText("");
            
            jLabel13.setText(prova.getRondaFinal().getDataIniRealitzacio().toString() + " a " + prova.getRondaFinal().getDataFiRealitzacio().toString());
            
            List<Inscripcio> entrada = new ArrayList<Inscripcio>();
            Inscripcio inscripcio = new Inscripcio();
            
            entrada =  remot.ObtenirInscrits(prova.getIdProva());
            nombreinscrits = entrada.size();
            
            DefaultTableModel modelo = new DefaultTableModel()
            {
                @Override
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
                }
            };
            
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.table.col1"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.table.col2"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.table.col3"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.detall.table.col4"));
            
            for (int i = 0;i<entrada.size();i++) { 
 
                inscripcio = entrada.get(i);
                Object[] fila = new Object[4];
                fila[0] = i + 1;
                fila[1] = inscripcio.getEstudiant().getIdUsuari();
                fila[2] = inscripcio.getEstudiant().getUniversitat();
                fila[3] = inscripcio.getDataInscripcio();
                
                modelo.addRow(fila); 
            } 
            this.jTable1.setModel(modelo); 
        } catch (Exception e){
            System.out.println(e.getMessage());
        }
           
    }
    
         /**
     * Retorna el tipus de ronda en que s'inscriurà l'estudiant per aquella prova
     * @return String     Tipus de ronda
     */  
    private String tipusderonda(Prova prova) {
        
        String sortida = "";
        
        if (prova.getRondaEliminatoria() == null){
            sortida = "F";
        } else {
                sortida = "E";
          } 
        
        return sortida;
    }    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
